package cn.acewill.yxd.yunxundian.ui.schedule;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.CheckTaskAdapter;
import cn.acewill.yxd.yunxundian.adapter.TimeSelectAdapter;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.SpinnerPopWin;


/**
 * Created by XXX on 2017/5/2.
 */

public class ScheduleCheckTaskActivity extends BaseActivity implements View.OnClickListener{

    private ListView mylist;
    private TextView yearSelect,monthSelect;
    private LinearLayout nodataBg;
    /*当前的时间*/
    private int mYear;
    /*保存选中的年月*/
    private int syear,smonth;
    private   CheckTaskAdapter adapter;
    /*请求的数据，亦是提交的数据*/
    private ArrayList<Schedule> Schedules;
    private TextView BgMsg;
    private ImageView checkImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_check_list);
        initView();
        getCurrentTime();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.muti_select_ok,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_ok:
                sendCheckData();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void initView(){
        Toolbar mytoolbar = (Toolbar) findViewById(R.id.myToolBar);
        mytoolbar.setTitle("");
        mytoolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(mytoolbar);
        mytoolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        this.mylist=(ListView) findViewById(R.id.myList);
        this.yearSelect= (TextView) findViewById(R.id.yearSelect);
        this.monthSelect= (TextView) findViewById(R.id.monthSelect);
        this.monthSelect.setOnClickListener(this);
        this.yearSelect.setOnClickListener(this);
        this.nodataBg= (LinearLayout) findViewById(R.id.nodataBg);
        this.BgMsg = (TextView)findViewById(R.id.BgMsg);
        this.checkImg = (ImageView) findViewById(R.id.checkImg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            /*年的选择*/
            case R.id.yearSelect:
                final ListView yearList=new ListView(this);
                yearList.setBackgroundColor(ContextCompat.getColor(this,R.color.white));
                final ArrayList<String> years=new ArrayList<>();
                years.add(mYear-2+"");
                years.add(mYear-1+"");
                years.add(mYear+"");
                years.add(mYear+1+"");
                years.add(mYear+2+"");
                TimeSelectAdapter adapter=new TimeSelectAdapter(this,years);
                yearList.setAdapter(adapter);
                final SpinnerPopWin popwindow=SpinnerPopWin.getInstance(this,yearList);
                popwindow.showPopupWindow(yearSelect);
                yearList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        popwindow.dismiss();
                        syear=Integer.parseInt(years.get(position));
                        yearSelect.setText(years.get(position)+"年");
                        getListInfo();
                    }
                });
                break;
            /*月的选择*/
            case R.id.monthSelect:
                final ListView monthList=new ListView(this);
                monthList.setBackgroundColor(this.getResources().getColor(R.color.white));
                final ArrayList<String> monlist=new ArrayList<>();
                for(int i=1;i<13;i++){
                    monlist.add(i+"");
                }
                TimeSelectAdapter adapter1=new TimeSelectAdapter(this,monlist);
                monthList.setAdapter(adapter1);
                final SpinnerPopWin popWin=SpinnerPopWin.getInstance(this,monthList);
                popWin.showPopupWindow(monthSelect);
                monthList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        popWin.dismiss();
                        smonth=Integer.parseInt(monlist.get(position));
                        monthSelect.setText(monlist.get(position)+"月");
                        getListInfo();
                    }
                });
                break;
        }
    }

    public void getCurrentTime(){
        Date date=new Date();
        SimpleDateFormat SDF_YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String time=SDF_YYYY_MM_DD.format(date);
        String[] array=time.split("-");
        mYear=Integer.parseInt(array[0]);

    }

    /*请求得到mylist数据*/
    public void getListInfo(){
        /*先判断年月是否为空*/
        String year=yearSelect.getText().toString();
        String month=monthSelect.getText().toString();
        if(TextUtils.isEmpty(year)||TextUtils.isEmpty(month)){
            return;
        }else {
            //有值直接请求网络
            Map<String, String> map = new HashMap<>();
            map.put("task","checkSchedule");
            map.put("empid", MainActivity.id+"");
            map.put("year", syear+"");
            map.put("month", smonth+"");
            try {
                OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (TextUtils.isEmpty(result)){//no data
                            mylist.setVisibility(View.GONE);
                            nodataBg.setVisibility(View.VISIBLE);
                            checkImg.setImageResource(R.mipmap.check_erro);
                            BgMsg.setText("无检验任务");
                            return;
                        }
                        String[] array = result.split("\\|");
                        if (array[0].equals("200")) {
                            Gson gson=new Gson();
                            Type typeList = new TypeToken<ArrayList<Schedule>>() {
                            }.getType();
                            Schedules = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                            adapter=new CheckTaskAdapter(ScheduleCheckTaskActivity.this, Schedules, new CheckTaskAdapter.SetStartTime() {
                                @Override
                                public void onTimeSet(String str,int position) {
                                    Schedule sch= Schedules.get(position);
                                    sch.setSchStartTime(str);
                                    adapter.notifyDataSetChanged();
                                }
                            });
                            mylist.setAdapter(adapter);
                            if (Schedules.size()==0){
                                mylist.setVisibility(View.GONE);
                                nodataBg.setVisibility(View.VISIBLE);
                                checkImg.setImageResource(R.mipmap.check_erro);
                                BgMsg.setText("无检验任务");
                            }else {
                                mylist.setVisibility(View.VISIBLE);
                                nodataBg.setVisibility(View.GONE);
                                adapter.notifyDataSetChanged();
                            }
                        }
                        else if(array[0].equals("301")){//已经通过校验
                            mylist.setVisibility(View.GONE);
                            nodataBg.setVisibility(View.VISIBLE);
                            checkImg.setImageResource(R.mipmap.check_correct);
                            BgMsg.setText("校验通过");
                        }else{
                            mylist.setVisibility(View.GONE);
                            nodataBg.setVisibility(View.VISIBLE);
                            checkImg.setImageResource(R.mipmap.check_erro);
                            BgMsg.setText("数据请求失败");
                        }
                    }
                    @Override
                    public void onFailture() {
                        BaseActivity.showAnimaDialog(ScheduleCheckTaskActivity.this,"网络开小差了，请重试");
                        mylist.setVisibility(View.GONE);
                        nodataBg.setVisibility(View.VISIBLE);
                        checkImg.setImageResource(R.mipmap.check_erro);
                        BgMsg.setText("网络开小差了，请稍后再试");
                    }
                },map);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*数据回传给后台*/
    public void sendCheckData() {
//        for (int i=0;i<Schedules.size();i++){
//            if (Schedules.get(i).getIsAssign()==1){
//                String time=Schedules.get(i).getSchStartTime();
//                if (time==null||TextUtils.isEmpty(time)){
//                    showToast("请将带*的必做任务设置开始时间");
//                    return;
//                }
//            }
//        }
        if (Schedules != null && Schedules.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("task", "saveCheckedSignSchedule");
            String jsonStr = JSON.toJSONString(Schedules);
            map.put("schjson", jsonStr);
            pubClass.Post(this, pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String[] resArry = result.split("\\|");
                    if (resArry[0].equals("200")) {
                        BaseActivity.showAnimaDialog(ScheduleCheckTaskActivity.this,"任务校验通过");
                    } else {
                        BaseActivity.showAnimaDialog(ScheduleCheckTaskActivity.this,"任务校验失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    BaseActivity.showAnimaDialog(ScheduleCheckTaskActivity.this,"网络开小差了，请重试");
                }
            });
        }
        else
        {
            BaseActivity.showAnimaDialog(this,"无提交日程信息。");
        }
    }
}
